import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { useModel } from 'umi';
import { CpasIcon, DevPopup } from "~/public/cpas-ui"
import { intl } from "@/utils";
import { confirm } from 'devextreme/ui/dialog';
import DataGrid, { Column, CustomRule, Editing, Item, Paging, PatternRule, RequiredRule, Summary, Toolbar, TotalItem } from "devextreme-react/data-grid"
import { getAccountInfo, getDateAdd, getDateDelete, getDateList, getDateUpdate, getSubjectType } from "./service";
import notify from "devextreme/ui/notify";
import moment from 'moment';
import { Guid } from "guid-factory/lib/Guid";
import { Lookup, SelectBox } from "devextreme-react";
import "./index.less"


export interface PropsDatas {
    width: string
    height: string
    button?: boolean
}

const SetDataGrid = React.forwardRef((props: PropsDatas, ref) => {
    const { width, height, button } = props;

    const { initialState } = useModel('@@initialState');
    const { zcbfid, dbname } = initialState?.curPart as API.CurPart;

    const DataGridRef = useRef<any>();
    const ClickValue = useRef<any>();
    const ColumnIndex = useRef<any>();
    const DeleteRef = useRef<any>();
    const eventsSaveData = useRef<any>([]);
    const dataRef = useRef<any>([]);
    const eventsNewRowKey = useRef<any>([]);
    const selectRefKey = useRef<any>([]);
    const periodValue = useRef<any>([]);

    const [perioddata, setPeriodData] = useState<any>([]);
    const [InfoDatas, setInfoData] = useState<any>([]);
    const [NewDatas, setNewData] = useState<any>({});
    const [PreviousValue, setPreviousValue] = useState<string>('');
    const [ByMonthData, setByMonthData] = useState<string>('');

    function compare(property: any) {
        return property.sort((a: { sjnd: { match: (arg0: RegExp) => string; }; }, b: { sjnd: { match: (arg0: RegExp) => string; }; }) => {
            const year_a = parseInt(a.sjnd.match(/^\d+/));
            const year_b = parseInt(b.sjnd.match(/^\d+/));
            return year_a - year_b;
        });
    }

    const getAccountInfos = async () => {
        if (dbname) {
            const InfoData = await getAccountInfo({ dbname });
            setInfoData(InfoData);
        }
    }
    useEffect(() => {
        getAccountInfos();
    }, [dbname])

    // 获取 期间列表
    // perioddata
    const getData = useCallback(async () => {
        const res = await getDateList({ zcbfid });
        const resdata = compare(res);
        setPeriodData(resdata);
    }, [zcbfid])

    // 自定义方法
    useImperativeHandle(ref, () => ({
        restYearTable: () => {
            getData();
            DataGridRef.current?.instance.refresh();
        },

        initData: () => { return perioddata },

        getData: () => {
            return eventsSaveData.current;
        },

        getPeriodData: () => {
            return dataRef.current
            // // const data_id = eventsSaveData.current[0].Data_ID;
            // // const state = InfoDatas.some((item: any) => item.Data_ID === eventsSaveData.current[0].Data_ID);
            // // console.log(state,'------');
            // // if (!state) {
            // //     const newPeriodData = {
            // //         id: zcbfid, nd: data_id, data_id: data_id, datname: "期间设置时创建", ByMonth: `${data_id}12`
            // //     }
            // //     return [newPeriodData];
            // // }
            // // return {};
            // console.log(eventsSaveData.current,'eventsSaveData.current-----');
            // // data.current.push()
            // const existingDataIds = InfoDatas.map((item: any) => item.Data_ID);
            // const newPeriodData = eventsSaveData.current
            //   .filter((item: any) => !existingDataIds.includes(item.Data_ID))
            //   .map((item: any) => ({
            //     id: zcbfid,
            //     nd: item.Data_ID,
            //     data_id: item.Data_ID,
            //     datname: "期间设置时创建",
            //     ByMonth: `${item.Data_ID}12`,
            //   }));
            //   return newPeriodData;
        },

        restYearAllData: () => {
            dataRef.current = [];
            eventsSaveData.current = [];
            eventsNewRowKey.current = [];
            ColumnIndex.current = null;
            DataGridRef.current?.instance.deselectAll();
        },

        checkContinuous: () => {
            return checkContinuousYear(perioddata);
        },

        checkDuplicate: () => {
            return checkDuplicateYear(perioddata)
        }
    }));

    // 判断 年度是否连续
    function checkContinuousYear(dataArray: any) {
        // 先按照时间顺序对对象数组进行排序
        dataArray.sort((a: { ADateS: number; }, b: { ADateS: number; }) => a.ADateS - b.ADateS);

        // 遍历数组，检查每个相邻对象的时间跨度是否为一年且连续
        for (let i = 0; i < dataArray.length - 1; i++) {
            const currDateEnd = new Date(dataArray[i].ADateE);
            const nextDateStart = new Date(dataArray[i + 1].ADateS);

            // 如果相邻对象的年份不连续，直接返回false
            if (currDateEnd.getFullYear() !== nextDateStart.getFullYear() - 1) {
                return false;
            }

            // 如果相邻对象的年份连续，但月份或日期的差距不为一年，也返回false
            if (
                currDateEnd.getMonth() !== 11
                || currDateEnd.getDate() !== 31
                || nextDateStart.getMonth() !== 0
                || nextDateStart.getDate() !== 1
            ) {
                return false;
            }
        }

        // 如果数组中所有对象的年月日都连续，则返回true
        return true;
    }

    //   判断 年度是否重复
    function checkDuplicateYear(arr: any) {
        // Step 1: 检查ID是否重复
        const years = arr.map((item: any) => parseInt(item.sjnd.match(/^\d+/)));
        for (let i = 0; i < years.length; i++) {
            for (let j = i + 1; j < arr.length; j++) {
                if (parseInt(arr[i].sjnd.match(/^\d+/)) === parseInt(arr[j].sjnd.match(/^\d+/))) {
                    return true;
                }
            }
        }

        // Step 2: 如果都没有重复，返回false
        return false;
    }

    const deleteData = async (selectdata: any) => {
        DeleteRef.current.show({
            title: "提示",
            okCallback: async () => {
                if (perioddata.length === 1) {
                    notify("至少保留一个期间", 'error', 2000)
                } else {
                    console.log(selectdata, 'selectdata----');
                    if (selectdata) {
                        periodValue.current = selectdata.Data_ID
                        const newData = { ...selectdata, rowState: 'delete' }
                        eventsSaveData.current.push(newData);
                        setPeriodData((item: any) => {
                            const newItemData: any[] = [...item];
                            const resFind = newItemData.filter((data: any) => data.id !== selectdata.id);
                            return compare(resFind);
                        });
                    }
                }
            }
        })
    }

    const rowStateChange = (rowData: any) => {
        const { data, key, type } = rowData;
        let newData: any;
        const ByMonth = data.ByMonth?.toString().substr(data.ByMonth.toString().length - 2);
        console.log(ByMonth, 'ByMonth----');

        const newKey = eventsNewRowKey.current.find((item: any) => item === key);

        let yearND = '';
        let yearNDID = '';
        let moothSND = '';
        let moothEND = '';
        let moothSDataND = '';
        let moothEDataND = '';

        if (data.ADateS && !data.ADateE) {
            yearNDID = `${moment(data.ADateS).year()}`;
            yearND = `${moment(data.ADateS).year()}年`;
            moothSND = `${moment(data.ADateS).month() + 1}`
            moothSDataND = moment(data.ADateS).format('YYYY-MM-DD');

            moothEND = `-12月`
            moothEDataND = `${yearNDID}-12-31`;

        }
        if (data.ADateE && !data.ADateS) {
            yearNDID = `${moment(data.ADateS).year()}`;
            yearND = `${moment(data.ADateE).year()}年`;
            moothEND = `-${moment(data.ADateE).month() + 1}月`
            moothEDataND = moment(data.ADateE).format('YYYY-MM-DD');
            moothSND = `1`
            moothSDataND = `${yearNDID}-01-01`;
        }

        if (data.ADateE && data.ADateS) {
            const yearQC = moment(data.ADateS).year();
            const yearQM = moment(data.ADateE).year();
            if (ColumnIndex.current === 1) {
                if (yearQC !== yearQM) {
                    yearNDID = `${moment(data.ADateS).year()}`;
                    yearND = `${moment(data.ADateS).year()}年`;
                    moothSND = `${moment(data.ADateS).month() + 1}`
                    moothSDataND = moment(data.ADateS).format('YYYY-MM-DD');
                    moothEND = `-12月`
                    moothEDataND = `${yearQC}-12-31`;
                } else {
                    if (new Date(data.ADateS) > new Date(data.ADateE)) {
                        yearNDID = `${moment(data.ADateS).year()}`;
                        yearND = `${moment(data.ADateS).year()}年`;
                        moothSND = `${moment(data.ADateS).month() + 1}`
                        moothSDataND = moment(data.ADateS).format('YYYY-MM-DD');

                        moothEND = `-12月`
                        moothEDataND = `${yearNDID}-12-31`;
                    } else {
                        yearNDID = `${moment(data.ADateS).year()}`;
                        yearND = `${moment(data.ADateS).year()}年`;
                        moothSND = `${moment(data.ADateS).month() + 1}`
                        moothSDataND = moment(data.ADateS).format('YYYY-MM-DD');

                        yearNDID = `${moment(data.ADateE).year()}`;
                        yearND = `${moment(data.ADateE).year()}年`;
                        moothEND = `-${moment(data.ADateE).month() + 1}月`
                        moothEDataND = moment(data.ADateE).format('YYYY-MM-DD');
                    }
                }
            }
            if (ColumnIndex.current === 2) {
                if (yearQC !== yearQM) {
                    console.log('cf');

                    moothSND = '1'
                    moothSDataND = `${yearQM}-01-01`;

                    yearNDID = `${moment(data.ADateE).year()}`;
                    yearND = `${moment(data.ADateE).year()}年`;
                    moothEND = `-${moment(data.ADateE).month() + 1}月`
                    moothEDataND = moment(data.ADateE).format('YYYY-MM-DD');
                } else {
                    if (new Date(data.ADateE) < new Date(data.ADateS)) {
                        moothSND = '1'
                        moothSDataND = `${yearQM}-01-01`;

                        yearNDID = `${moment(data.ADateE).year()}`;
                        yearND = `${moment(data.ADateE).year()}年`;
                        moothEND = `-${moment(data.ADateE).month() + 1}月`
                        moothEDataND = moment(data.ADateE).format('YYYY-MM-DD');
                    } else {
                        yearNDID = `${moment(data.ADateS).year()}`;
                        yearND = `${moment(data.ADateS).year()}年`;
                        moothSND = `${moment(data.ADateS).month() + 1}`
                        moothSDataND = moment(data.ADateS).format('YYYY-MM-DD');

                        yearNDID = `${moment(data.ADateE).year()}`;
                        yearND = `${moment(data.ADateE).year()}年`;
                        moothEND = `-${moment(data.ADateE).month() + 1}月`
                        moothEDataND = moment(data.ADateE).format('YYYY-MM-DD');
                    }
                }
            }
            if (ColumnIndex.current === 3) {
                moothSND = `${moment(data.ADateS).month() + 1}`
                moothSDataND = moment(data.ADateS).format('YYYY-MM-DD');
                yearND = `${moment(data.ADateE).year()}年`;
                moothEND = `-${moment(data.ADateE).month() + 1}月`
                moothEDataND = moment(data.ADateE).format('YYYY-MM-DD');
            }
        }

        if (newKey) {
            newData = { Data_ID: yearNDID, id: key, sjnd: `${yearND}${moothSND}${moothEND}`, ADateS: moothSDataND, ADateE: moothEDataND, ByMonth: data.ByMonth ? `${yearNDID}${ByMonth}` : `${yearNDID}12`, rowState: 'insert' }
        } else {
            if (type === 'insert') {
                newData = { Data_ID: yearNDID, id: key, sjnd: `${yearND}${moothSND}${moothEND}`, ADateS: moothSDataND, ADateE: moothEDataND, ByMonth: data.ByMonth ? `${yearNDID}${ByMonth}` : `${yearNDID}12`, rowState: 'insert' }
                eventsNewRowKey.current.push(key);
            } else if (type === 'update') {
                newData = { Data_ID: yearNDID, id: key, sjnd: `${yearND}${moothSND}${moothEND}`, ADateS: moothSDataND, ADateE: moothEDataND, ByMonth: data.ByMonth ? `${yearNDID}${ByMonth}` : `${yearNDID}12`, rowState: 'update', where: { guid: key } }
            } else {
                newData = { Data_ID: yearNDID, id: key, sjnd: `${yearND}${moothSND}${moothEND}`, ADateS: moothSDataND, ADateE: moothEDataND, ByMonth: data.ByMonth ? `${yearNDID}${ByMonth}` : `${yearNDID}12`, rowState: 'delete' }
            }
        }

        if (newData.rowState !== 'delete') {
            setPeriodData((item: any) => {
                let newItemData = [...item];
                const resFind = newItemData.find((data: any) => data.id && data.id === key);
                if (resFind) {
                    newItemData = newItemData.map((item: { id: string; }) => {
                        if (item.id === key) {
                            return newData;
                        }
                        return item;
                    });
                } else {
                    newItemData.push(newData);
                }
                return compare(newItemData);
            })
        }
        return newData;
    }

    const SavedData = (e: any) => {
        if (e.changes.length) {
            const { key } = e.changes[0];
            const newData = rowStateChange(e.changes[0]);
            const resFind = eventsSaveData.current.find((data: any) => data.id && data.id === key);
            if (resFind) {
                // 修改更改的值
                eventsSaveData.current = eventsSaveData.current.map((item: { id: string; }) => {
                    if (item.id === key) {
                        return newData;
                    }
                    return item;
                });
            } else {
                eventsSaveData.current.push(newData);
            }

        }
    }


    const contentReady = (e: any) => {
        const idnex = DataGridRef.current?.instance.getVisibleRows();
        const aa = idnex.filter((item: any) => {
            if (item.data.id === NewDatas.id) {
                return item
            }
        });
        if (aa.length >= 1) {
            DataGridRef.current?.instance.deselectRows(selectRefKey.current.key)
            if (button) DataGridRef.current?.instance.selectRowsByIndexes(aa[0].rowIndex);
        } else {
            if (button) DataGridRef.current?.instance.selectRowsByIndexes(0);
        }
    }


    // 右击 的显示操作
    const dataMenuItems = (e: any) => {
        if (button) {
            // 数据上的菜单
            if (e.target == 'content' && e.row?.rowType == 'data') {
                e.items = [
                    {
                        icon: 'add',
                        text: intl('audit.paper.add', '添加'),
                        onItemClick: (() => {
                            if (ClickValue.current) {
                                const yearMatch = ClickValue.current.sjnd.match(/\d{4}/);
                                const tempND = yearMatch[0] * 1 - 1;
                                const newData = {
                                    id: Guid.newGuid(), Data_ID: `${tempND}`, sjnd: `${tempND}年1-12月`, ADateS: `${tempND}-01-01`, ADateE: `${tempND}-12-31`, ByMonth: `${tempND}12`, rowState: 'insert'
                                };

                                eventsNewRowKey.current.push(newData.id);
                                eventsSaveData.current.push(newData);
                                setPeriodData((item: any) => {
                                    const newItemData = [...item];
                                    newItemData.push(newData);
                                    return compare(newItemData);
                                })
                                setNewData(newData)
                            }
                        }),
                    },
                    {
                        icon: 'trash',
                        text: intl('audit.paper.del', '删除'),
                        onItemClick: (async () => {
                            deleteData(e.row.data);
                        })
                    },
                ]
            }
        }
    }

    // 对应账套 现不做编辑 后期看变化
    // const onValueChanged = async (cell: any, e: any) => {
    //     cell.setValue(e.value.Data_ID);
    //     setPreviousValue(e.value.Data_ID);
    //     // const type = await getSubjectType({
    //     //     dbname,
    //     //     Data_ID: e.value.Data_ID
    //     // });
    //     // setByMonthData(type[0].name)
    //     // console.log(type, 'r-------');
    //     // setPeriodData(r);
    // }
    // const statusEditorRender = (cell: any) => {
    //     return <SelectBox
    //         dataSource={InfoDatas}
    //         defaultValue={cell.value}
    //         {...cell.column.lookup}
    //         displayExpr="Data_ID"
    //         onValueChanged={(e) => onValueChanged(cell, e)}
    //     />;
    // }


    return (
        <div style={{ width: "100%", height: "100%", display: 'flex', flexDirection: 'column' }}>
            {useMemo(() => {
                return <DataGrid
                    className='PaperDevSortableGrid devHeadersCenter'
                    width={width}
                    height={button ? '79%' : "100%"}
                    className='HomeGrid'
                    keyExpr="id"
                    dataSource={perioddata}
                    allowColumnReordering={true}
                    allowColumnResizing={true}
                    allowHeaderFiltering={false}
                    showBorders={true}
                    showRowLines={true}
                    ref={DataGridRef}
                    // // focusedRowEnabled={true}
                    // focusedRowIndex={0}
                    onContentReady={contentReady}
                    // 显示menu
                    onContextMenuPreparing={dataMenuItems}
                    // 失焦 保存数据
                    onSaved={SavedData}
                    onSelectionChanged={({ selectedRowsData }: any) => {
                        if (selectedRowsData[0] && button) {
                            ClickValue.current = selectedRowsData[0];
                        }
                    }}
                    onCellClick={(v) => {
                        // console.log(v, '-------v');
                        selectRefKey.current = v
                        if (v.rowType === "header") return;
                        if (v.rowIndex !== -1) {
                            console.log(v.rowIndex, 'v.rowIndex---');
                            DataGridRef.current?.instance.selectRows(v.rowIndex, true);
                            ClickValue.current = v.row.data;
                            ColumnIndex.current = v.columnIndex;
                        }
                    }}
                    selection={{ mode: 'single' }}
                    columnResizingMode="widget"
                    columnMinWidth={70}
                    editing={{
                        // mode: 'batch',
                        mode: 'cell',
                        allowUpdating: button ? true : false,
                        allowAdding: button ? true : false,
                        startEditAction: 'click',
                        allowDeleting: false
                    }}
                >
                    <Paging enabled={false} />
                    <Toolbar>
                        <Item
                            location='before'
                            render={() => {
                                return <span style={{ fontWeight: "600", fontSize: "14px" }}>期间设置</span>
                            }}
                        />
                    </Toolbar>
                    <Column
                        caption={'期间'}
                        dataField="sjnd"
                        alignment='center'
                        allowEditing={false}
                        allowResizing={true}
                        allowHeaderFiltering={false}
                        width={110}
                    />
                    <Column
                        caption={'期初'}
                        dataField="ADateS"
                        alignment='center'
                        dataType="date"
                        allowResizing={true}
                        allowHeaderFiltering={false}
                    />
                    <Column
                        caption={'期末'}
                        dataField="ADateE"
                        alignment='center'
                        dataType="date"
                        allowResizing={true}
                        allowHeaderFiltering={false}
                    />
                    <Column
                        caption={'对应账套'}
                        dataField="Data_ID"
                        alignment='center'
                        dataType="Data_ID"
                        allowEditing={false}
                        allowResizing={true}
                        allowHeaderFiltering={false}
                    // 目前 不让设置
                    // editCellRender={statusEditorRender}
                    />
                    <Column
                        caption={'账套期间'}
                        dataField="ByMonth"
                        alignment='center'
                        allowEditing={false}
                        allowResizing={true}
                        allowHeaderFiltering={false}
                    />
                    <Column
                        caption={'操作'}
                        alignment='center'
                        visible={button ? true : false}
                        fixed={true}
                        fixedPosition='right'
                        cellRender={(cell: any) => {
                            return <CpasIcon type="icon-delete" onClick={() => {
                                deleteData(cell.data);
                            }} />
                        }}
                    />
                </DataGrid >
            }, [perioddata])}
            {
                button ?
                    <div className="Text_Style" onClick={() => {
                        if (ClickValue.current) {
                            const yearMatch = ClickValue.current.sjnd.match(/\d{4}/);
                            const tempND = yearMatch[0] * 1 - 1;
                            const newData = {
                                id: Guid.newGuid(), Data_ID: `${tempND}`, sjnd: `${tempND}年1-12月`, ADateS: `${tempND}-01-01`, ADateE: `${tempND}-12-31`, ByMonth: `${tempND}12`, rowState: 'insert'
                            };
                            eventsNewRowKey.current.push(newData.id);
                            eventsSaveData.current.push(newData);
                            setPeriodData((item: any) => {
                                const newItemData = [...item];
                                newItemData.push(newData);
                                return compare(newItemData);
                            })
                            setNewData(newData);

                            console.log(newData, 'newData-----');
                            console.log(InfoDatas, 'InfoDatas----');

                            const state = InfoDatas.some((item: any) => item.Data_ID === newData.Data_ID);
                            console.log(state, 'state----');
                            if (!state) {
                                const newPeriodData = {
                                    id: zcbfid, nd: tempND, data_id: tempND, datname: "期间设置时创建", ByMonth: `${tempND}12`
                                }
                                dataRef.current.push(newPeriodData);
                            } else {
                                return {};
                            }
                        }
                    }} >
                        <span><CpasIcon type="icon-add-circle1" /> 新建</span>
                    </div>
                    : ''
            }
            <DevPopup.Default ref={DeleteRef} width={80} height={200} >
                {() => {
                    return <span>是否要删除此记录？</span>
                }}
            </DevPopup.Default>
        </div>
    )
})
export default React.memo(SetDataGrid);
